package com.esunrising.esungsc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esunrising.esungsc.common.utils.ESUNGSCUtil;
import com.esunrising.esungsc.common.utils.HttpUtil;
import com.esunrising.esungsc.config.GSCAPIConfig;
import com.esunrising.esungsc.dao.AccountTitleDao;
import com.esunrising.esungsc.entity.TApiKm;
import com.esunrising.esungsc.service.AccountTitleService;
import com.esunrising.esungsc.service.GSCService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class AccountTitleServiceImpl extends BaseServiceImpl<AccountTitleDao, TApiKm> implements AccountTitleService {

    @Resource
    private GSCAPIConfig gscapiConfig;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private GSCService gscService;

    @Resource
    private AccountTitleDao dao;


    @Override
    public List<TApiKm> accountTitleResult(String dwbh, String orgCode, String code, String year) {
        String orgId = "";
        String ledger = "";
        String type = "pz-test";

        String baseUrl = gscapiConfig.getBaseUrl();
        String accountTitle = gscapiConfig.getApis().get("getBfAccountTitle");
        String url = baseUrl + accountTitle;

        //添加query参数
        String uri = HttpUtil.putQueryParam(url, null);

        //设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.addAll(new LinkedMultiValueMap<>(gscapiConfig.getRequestHeaders()));

        //准备请求体参数
        HashMap<String, Object> httpBody = new HashMap<>();
        httpBody.put("code", code);
        httpBody.put("year", year);

        //组织参数
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(httpBody, httpHeaders);

        //发送请求
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);

        String msg = " ";

        //解析返回结果
        if (response.getStatusCodeValue() == 200){
            //数据请求成功
            String responseBody = response.getBody();

            msg = "获取成功";
            // 记录日志
            gscService.saveLog(dwbh, orgId, orgCode, ledger, type, msg);
            // 更新调用时间记录
            gscService.updateSyncTime(dwbh, orgId, orgCode, ledger, type, LocalDateTime.now());
            return ParseAccountTitle(responseBody);
        }else {

            // 接口调用失败
            msg = "接口调用失败";
            // 记录日志
            gscService.saveLog(dwbh, orgId, orgCode, ledger, type, msg);

            System.out.println(response.getStatusCodeValue());
            System.out.println(response.getStatusCode());
            System.out.println(response.getHeaders());
            System.out.println(response.getBody());
            return  null;
        }

    }

    @Override
    public void saveTApiKmList(List<TApiKm> tApiKmList) {
        for (TApiKm tApiKm : tApiKmList) {
            System.out.println("单个Tapikm值"+tApiKm);
//            try {
//                dao.save(tApiKm);
//            } catch (Exception e) {
//                System.err.println("保存失败: " + e.getMessage());
//                e.printStackTrace();
//            }
             syncSave(tApiKm);
        }
    }

    @Override
    public void syncSave(TApiKm entity) {
        // 如果存在，则先删除
        Optional<TApiKm> byId = dao.findById(entity.getId());
        byId.ifPresent( doc -> {
            dao.deleteById(doc.getId());
        });
        // 保存数据
        super.save(entity);
    }
    private List<TApiKm> ParseAccountTitle(String responseBody) {

        JSONObject jsonObject = JSONObject.parseObject(responseBody);
        Boolean result = jsonObject.getBoolean("result");
        String code = jsonObject.getString("code");

        if (result){
            log.info("数据请求成功");
            JSONArray value = jsonObject.getJSONArray("value");
            System.out.println("解析value值：："+value);
            List<TApiKm> tApiKmList = new ArrayList<>();
            for (int i = 0; i < value.size(); i++) {
                JSONObject valueJSONObject = value.getJSONObject(i);
                TApiKm tApiKm = ESUNGSCUtil.jsonObject2ApiKm(valueJSONObject);
                tApiKmList.add(tApiKm);
            }
            return  tApiKmList;
        }else {
            log.error("数据请求失败");
            return null;
        }
    }
}
